package com.poetry.common.hander;

import com.poetry.common.entity.common.R;
import com.poetry.common.exception.ServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 监听全局异常
 * @author mengxj
 */
@RestControllerAdvice
@Component
public class HandleException {

    @ExceptionHandler(Exception.class)
    public <T> R<T> handleException(Exception e){
        return this.logAndReturn(e);
    }

    @ExceptionHandler(ServiceException.class)
    public <T> R<T> handleServiceException(ServiceException e){
        return this.logAndReturn(e);
    }

    private <T> R<T> logAndReturn(Throwable e){
        System.out.println(e.getMessage());
        return R.msg(String.format("%s: %s", e.getClass(), e.getMessage()));
    }
}
